{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 2.1.5 Algebraic Multigrid Methods\n",
    "\n",
    "Algebraic multigrid methods (AMG) build a multigrid hierarchy from the given matrix. In contrast to geometric multigrid methods, they do not need a mesh hierarchy. Just one finite element mesh is enough.\n",
    "\n",
    "AMG takes profit from providing the type of problem (Poisson equation, elasticity, Maxwell, ...).\n",
    "\n",
    "NGSolve comes with builtin AMG solvers for scalar equations, and for Maxwell equations. It provides also  interfaces to external, parallel AMG solvers (hypre, gamg, ...)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The builtin *h1amg*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `h1amg` preconditioner works for symmetric, scalar problems with nodal degrees of freedom. \n",
    "It uses unsmoothed agglomeration for the generation of coarse spaces.\n",
    "\n",
    "The coarsening of degrees of freedom is steered by the strength of connections between dofs, one may think of a network of resistors. For this, one finds edge-based weights $w_E$ such that the energy norm is equivalent to the weighted sum of squared differences:\n",
    "\n",
    "$$\n",
    "u^T A u \\approx \\sum_{{\\text edges} E} w_E \\, (u_{E_1} - u_{E_2})^2\n",
    "$$\n",
    "\n",
    "$w_E$ is the edge-weight (the conductivity of each resistor), and $E_1$ and $E_2$ are the vertex numbers of the end-points of the edge $E$. The right hand side is a norm represented by a surrogate matrix $\\tilde A$. \n",
    "\n",
    "The first task is to determine the edge-weights $w_E$. If one has access to element-matrices (instead of the assembled matrix), one has better possibilities. One may compute Schur complements with respect to all edges of each element, which gives a surrogate matrix for each element. Then sum up the weights (conductivities) of all elements sharing the edge.\n",
    "\n",
    "To have access to element matrices, the setup of the surrogate matrix is included into the assembling loop. Thus, the workflow is to \n",
    "\n",
    "1. define the biliear-form\n",
    "2. define the h1amg preconditioner, which registers at the bilinear-form\n",
    "3. finally assemble the bilinear-form, which also runs the setup of the preconditioner"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ngsolve import *\n",
    "from ngsolve.la import EigenValues_Preconditioner\n",
    "\n",
    "# minimize memory requirements by switching off tables which we don't need here\n",
    "import netgen.meshing\n",
    "netgen.meshing.Mesh.EnableTableClass(\"edges\", False)\n",
    "netgen.meshing.Mesh.EnableTableClass(\"faces\", False)\n",
    "\n",
    "with TaskManager():\n",
    "    mesh = Mesh(unit_cube.GenerateMesh(maxh=0.1))\n",
    "    for l in range(3): mesh.Refine()    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fes = H1(mesh, order=1, order_policy=ORDER_POLICY.CONSTANT)  # todo: fix withtout edge/face tables\n",
    "fes = FESpace(\"nodal\", mesh, order=1)\n",
    "print (\"ndof=\", fes.ndof)\n",
    "u,v = fes.TnT()\n",
    "a = BilinearForm(grad(u)*grad(v)*dx + 1e-3*u*v*dx)\n",
    "pre = Preconditioner(a, \"h1amg\")\n",
    "with TaskManager():\n",
    "    a.Assemble();\n",
    "    lam = EigenValues_Preconditioner(a.mat, pre.mat)\n",
    "    print (list(lam[0:3]), '...', list(lam[-3:-1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## H(curl) - AMG\n",
    "\n",
    "The `hcurlamg` is an implementation of the amg from [Reitzinger and Schöberl: An algebraic multigrid method for finite element discretizations with edge elements](https://onlinelibrary.wiley.com/doi/abs/10.1002/nla.271?casa_token=SGxs8UGF--IAAAAA:53O8vbFJpEkXyuSu4T2yzP7BKBJecdNoFdEvLqUKT_ZRUMn0U5FM--SqGXRiQu38et4xuMPg6cPUgfUBoQ).\n",
    "\n",
    "It is based on a surrogate matrix for a weighted $H(\\operatorname{curl})$ norm discretized by lowest order Nedelec elements:\n",
    "\n",
    "$$\n",
    "\\| u \\|_{L_2, \\sigma}^2 + \\| \\operatorname{curl} u \\|_{L_2, \\nu}^2\n",
    "\\approx \\sum_E w_E \\, \\Big(\\int_E u_{\\tau} \\Big)^2 + \n",
    "\\sum_F w_F \\, \\Big(\\int_F \\operatorname{curl}_n u \\Big)^2\n",
    "$$\n",
    "\n",
    "The smoother is a Hiptmair smoother, where a Gauss-Seidel smoother is combined with another Gauss-Seidel smoother for the potential space.\n",
    "\n",
    "The key is a coarsening which preserves the de Rham sequence over all levels, such that Hiptmair's smoother is effective also on coarser levels.\n",
    "\n",
    "More recent, robust coarsening strategies are developed in [B. Schwarzenbacher: Robust algebraic solvers for electromagnetics, Master's Thesis](https://repositum.tuwien.at/handle/20.500.12708/1351)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ngsolve import *\n",
    "from ngsolve.la import EigenValues_Preconditioner\n",
    "# switch on again generation of tables  \n",
    "import netgen.meshing\n",
    "netgen.meshing.Mesh.EnableTableClass(\"edges\", True)\n",
    "netgen.meshing.Mesh.EnableTableClass(\"faces\", True)\n",
    "\n",
    "with TaskManager():\n",
    "    mesh = Mesh(unit_cube.GenerateMesh(maxh=0.1))\n",
    "    for l in range(1): mesh.Refine()    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fes = HCurl(mesh, order=0)\n",
    "print (\"ndof = \", fes.ndof)\n",
    "u,v = fes.TnT()\n",
    "\n",
    "a = BilinearForm(curl(u)*curl(v)*dx + 0.01*u*v*dx)\n",
    "pre = Preconditioner(a, \"hcurlamg\")\n",
    "with TaskManager():\n",
    "    a.Assemble()\n",
    "    lam = EigenValues_Preconditioner(a.mat, pre.mat)\n",
    "    print (list(lam[0:3]), '...', list(lam[-3:-1]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = LinearForm(curl(v)[2]*dx).Assemble()\n",
    "gfu = GridFunction(fes)\n",
    "from ngsolve.krylovspace import CGSolver\n",
    "\n",
    "inv = CGSolver(a.mat, pre.mat, plotrates=False, maxiter=200)\n",
    "\n",
    "gfu.vec[:] = inv*f.vec"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
